package findKthToTail;

public class Solution {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        ListNode l6 = new ListNode(6);
        ListNode l7 = new ListNode(7);
        ListNode l8 = new ListNode(8);

        l1.setNext(l2);
        l2.setNext(l3);
        l3.setNext(l4);
        l4.setNext(l5);
        l5.setNext(l6);
        l6.setNext(l7);
        l7.setNext(l8);

        Solution s =  new Solution();
        int var = s.findKthToTail(l1, 1).getVar();
        System.out.println(var);
        System.out.println(s.findKthToTail2(l1,2).getVar());

    }
    public ListNode findKthToTail2(ListNode head , int k){

        int i = k -1;
        ListNode last = head ;
        ListNode last1 = head ;

        while(i-->0){
            last = last.getNext();
        }
        while(last.getNext() != null){
            last = last.getNext();
            last1 = last1.getNext();
        }
        return last1 ;
    }
    public ListNode findKthToTail(ListNode head , int k){
        ListNode next = head ;
        int length = 0 ;
        int kthFromHead = 0 ;
        do{
            length++;
        }while((next=next.getNext())!=null);
        kthFromHead = length - k ;
        if(kthFromHead<0){
           return null ;
        }
        next = head ;
        while(kthFromHead-->0){
            next = next.getNext();
        }

        return next;
    }
}
